import { Dialog } from 'antd-mobile'
import Router from 'next/router'

// 实名认证状态检查
const isAuthenticated = () => {
  if (typeof window === 'undefined') return false
  console.log('isAuthenticated', localStorage.getItem('isAuthenticated'))
  return localStorage.getItem('isAuthenticated') === '111'
}

// 修改装饰器实现
export function RequireAuth() {
  return function (
    target: Object,
    key: string | symbol,
    descriptor: TypedPropertyDescriptor<any>
  ): TypedPropertyDescriptor<any> {
    // 保存原始方法
    const originalMethod = descriptor.value

    // 修改方法实现
    descriptor.value = function (...args: any[]) {
      // 服务端渲染时直接返回
      if (typeof window === 'undefined') {
        return originalMethod.apply(this, args)
      }

      // 返回一个 Promise
      return new Promise(async (resolve) => {
        if (!isAuthenticated()) {
          const result = await Dialog.confirm({
            title: '需要实名认证',
            content: '该功能需要实名认证后才能使用，是否立即去认证？',
            confirmText: '去认证',
            cancelText: '取消'
          })

          if (result) {
            Router.push('/verify-identity')
            resolve(false)
            return
          }
          resolve(false)
          return
        }

        // 已认证，执行原方法
        const result = await originalMethod.apply(this, args)
        resolve(result)
      })
    }

    return descriptor
  }
} 